<?php

namespace App\Http\Controllers;

use Alipay\OpenAPISDK\Util\AlipaySignature;
use App\Models\Lz\Aspnetuser;
use App\Models\Lz\Depositrecord;
use App\Models\Lz\Mylog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class NotifyController extends Controller
{

//    private $appid = '2021004170645344';
//    protected $privateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCwA6+7LuBROUMF1MK10mrv8H1xK/9zB6PUjF+3mvaTCE4+OLZSIU72UuGoXkeZIQE9VEwqPFqTAsvWBuBOGim26frlBJxh0zUX+hwyFGxPiM55jvI+YCWo3wEfOT9QUk8Lw3U0H8C/VLl6xd7hbLb0ajbjDfPQEP86yCigngZfI+E0WpOGiVcl1Qp+vXqzWJi0iGFI2W7dBLbik+mRE1wKOjwU3KD1EdyWbLz8Eu69q4/5ReiYKi+nZTPWRSdxqwdsY1EoJECaj2M38O7iaKGhpf9SkeT7A+6n61C8DfBOZSV2ipkVp6azAAu6+SkJIFsDxuRzi1YZ3HZpq7nVlhdBAgMBAAECggEALfaoez8AgPVtFSa8OfLazhGFEHqm2IkUNTr6+91Rqo+urvzsT4I3NofqOad1Fv3RbwyGXzknheBjDl75UCvw3L05MXkExV78LGi52DIRHqvhD0lO5Q8ChpjFmDvA1t7HmZDPGG96S/x5+x+U1lUnaaga8SwBkUH/BICka10Y2Nr8yDAjfkItRiw0PPcBRwOOKkNXLtDXrqVFjMgb0vpna3DovyVkfW4FaADoA4M63KpPvxF+BfYDrN9BmiKoBrIjWrVCAArgG/2W8lBoAZKuP0IdG6YFfXLE475hltDmPDk31rXkVm3SXSqSiOAIzx8QROHMgFU+aHcYIN/VuvucaQKBgQDeA8nwVOz7iHnnfqsT9MUjVel9fMuWE7p+54doMg0VtlSOQccXUBSttYGkL/xKktaQid5JOu5qIN7K/f23qbVWWnhtsrvU2imQqMkz7qZaNKmOU2POMT7TEGFijvJ2ck6o9w4cCnMLCxgo3scs3ow6oE8crRkJ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4ayn5IjQ1+7AWvzHMegz2oiSr0WYy9Q4KLxMC+KHQIDAQAB';

    protected $appid = null;
    protected $privateKey = null;
    protected $publicKey = null;

    public function __construct()
    {
        $config = config('alipay.pc_pay');
        $this->appid = $config['appid'];
        $this->privateKey = $config['app_private_key'];
        $this->publicKey = $config['public_key'];

//        $this->appid = '2021004170645344';
//        $this->privateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCwA6+7LuBROUMF1MK10mrv8H1xK/9zB6PUjF+3mvaTCE4+OLZSIU72UuGoXkeZIQE9VEwqPFqTAsvWBuBOGim26frlBJxh0zUX+hwyFGxPiM55jvI+YCWo3wEfOT9QUk8Lw3U0H8C/VLl6xd7hbLb0ajbjDfPQEP86yCigngZfI+E0WpOGiVcl1Qp+vXqzWJi0iGFI2W7dBLbik+mRE1wKOjwU3KD1EdyWbLz8Eu69q4/5ReiYKi+nZTPWRSdxqwdsY1EoJECaj2M38O7iaKGhpf9SkeT7A+6n61C8DfBOZSV2ipkVp6azAAu6+SkJIFsDxuRzi1YZ3HZpq7nVlhdBAgMBAAECggEALfaoez8AgPVtFSa8OfLazhGFEHqm2IkUNTr6+91Rqo+urvzsT4I3NofqOad1Fv3RbwyGXzknheBjDl75UCvw3L05MXkExV78LGi52DIRHqvhD0lO5Q8ChpjFmDvA1t7HmZDPGG96S/x5+x+U1lUnaaga8SwBkUH/BICka10Y2Nr8yDAjfkItRiw0PPcBRwOOKkNXLtDXrqVFjMgb0vpna3DovyVkfW4FaADoA4M63KpPvxF+BfYDrN9BmiKoBrIjWrVCAArgG/2W8lBoAZKuP0IdG6YFfXLE475hltDmPDk31rXkVm3SXSqSiOAIzx8QROHMgFU+aHcYIN/VuvucaQKBgQDeA8nwVOz7iHnnfqsT9MUjVel9fMuWE7p+54doMg0VtlSOQccXUBSttYGkL/xKktaQid5JOu5qIN7K/f23qbVWWnhtsrvU2imQqMkz7qZaNKmOU2POMT7TEGFijvJ2ck6o9w4c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hw08USKdMdJLqxvJzDZ8KPwtv4ayn5IjQ1+7AWvzHMegz2oiSr0WYy9Q4KLxMC+KHQIDAQAB';


    }


    public function pay(Request $request)
    {
        $params = $request->all();
        $dir = 'storage/pay_notify/' . date('Ymd');
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        file_put_contents($dir . '/notify_req.json', json_encode($params, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        if (AlipaySignature::rsaCheckV1($params, $this->publicKey)) {
            $this->orderHandle($params);
        } else {
            file_put_contents($dir . '/notify_error.json', json_encode($params, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        }
        echo "success";
    }

    protected function orderHandle($params)
    {
        $outTradeNo = $params['out_trade_no'];
        $aliTradeNo = $params['trade_no'];
        $receiveAmount = $params['receipt_amount'];
        $tradeStatus = $params['trade_status'];
        $order = Depositrecord::query()->where('ID', $outTradeNo)->first();
        if (empty($order)) {
            return false;
        }

        $dir = 'storage/pay_notify/' . date('Ymd');
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        $authAppid = $params['app_id'];
        if ($authAppid != $this->appid) {
            file_put_contents($dir . '/notify_auth_err.json', json_encode([
                    'msg'  => '非法', 'time' => date('Y-m-d H:i:s'),
                    'data' => $params,
                ], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            return false;
        }
        $success = 'TRADE_SUCCESS';
        if ($order->TradeStatus == $success) {
            return true;
        }
        $update['NotifyJson'] = $params;
        if ($tradeStatus != $success) {
            $update['TradeStatus'] = $tradeStatus;
            $update['Message'] = '交易异常';
            $update['OrderStatus'] = 10;
            Depositrecord::query()->where('ID', $outTradeNo)->update($update);
            return true;
        }
        DB::beginTransaction();
        try {
            $payTime = $params['gmt_payment'];
            $update['Message'] = '支付成功';
            $update['PayTime'] = $payTime;
            $update['SuccessTime'] = $payTime;
            $update['TradeStatus'] = $success;
            $update['TradeNo'] = $aliTradeNo;
            $update['ReceiveAmout'] = $receiveAmount;
            $update['OrderStatus'] = 20;
            $update['DepositRecordStatus'] = 1;
            Depositrecord::query()->where('ID', $outTradeNo)->update($update);
            if ($order->IsRecharge) {
                DB::commit();
                return false;
            }
            // 添加进件
            $count = $order->Count;
            $userId = $order->PayUserId;
            $user = Aspnetuser::query()->where('Id', $userId)->first();
            if (empty($user)) {
                file_put_contents($dir . '/notify_auth_err.json', json_encode([
                        'msg'  => '未查询到用户信息', 'time' => date('Y-m-d H:i:s'),
                        'data' => $params,
                    ], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                DB::commit();
                return false;
            }

            $typeName = '进件';
            $field = 'IncomeAmout';
            if ($order->Type == 1) {
                $typeName = '短信';
                $field = 'SmsAmout';
            }
            // 更新进件
            Aspnetuser::query()->where('Id', $userId)->lockForUpdate()->update([
                $field => DB::raw($field . '+' . $count),
            ]);
            // 记录日志
            $amount = bcadd($order->Amout, 0, 2);
            Mylog::query()->insert([
                ['Type' => 0, 'Content' => sprintf('用户【%s】%s充值【%s】元', $order->PayUserName, $typeName, $amount), 'DateTime' => date('Y-m-d H:i:s'), 'UserID' => $userId],
                ['Type' => 0, 'Content' => sprintf('用户【%s】新增%s 【%s】 条', $order->PayUserName, $typeName, $count), 'DateTime' => date('Y-m-d H:i:s'), 'UserID' => $userId],
            ]);
            Depositrecord::query()->where('ID', $outTradeNo)->update([
                'IsRecharge'          => 1,
                'DepositRecordStatus' => 2,
            ]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            file_put_contents($dir . '/notify_insert_err.json', json_encode([
                    'msg'  => '插入数据库异常', 'time' => date('Y-m-d H:i:s'),
                    'data' => $params, 'exception' => $e->getMessage(),
                ], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        }


        return true;
    }
}
